// wx.request封装
const requestGet = (url, data, cb, errcb) => {
  wx.showLoading({
    title: '加载中',
  });
  wx.request({
    url: 'https://jgj.hzlingdian.com/' + url,
    method: "GET",
    data: data,
    header: {
      'Content-Type': 'application/json',
    },
    success: function (res) {
      if (typeof cb == "function") {
        wx.hideLoading();
        if (res.statusCode == 200) {
          cb(res.data);
        } else {
          errcb(res);
        }
      }
    },
    fail: function (res) {
      if (typeof errcb == "function") {
        wx.hideLoading();
        errcb(res);
      }
    }
  })
}

const requestPost = (url, data, cb, errcb)=> {
  wx.showLoading({
    title: '加载中',
  });
  wx.request({
    url: 'https://jgj.hzlingdian.com/' + url,
    method: "POST",
    data: data,
    header: {
      'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
    },
    success: function (res) {
      if (typeof cb == "function") {
        wx.hideLoading();
        if (res.statusCode == 200) {
          cb(res.data);
        } else {
          errcb(res);
        }
      }
    },
    fail: function (res) {
      if (typeof errcb == "function") {
        wx.hideLoading();
        errcb(res);
      }
    }
  })
}

/*获取小程序当前页url*/
const getCurrentPageUrl=() =>  {
  var pages = getCurrentPages()    //获取加载的页面
  var currentPage = pages[pages.length - 1]    //获取当前页面的对象
  var url = currentPage.route    //当前页面url
  return url  //例如：pages/index/index
}

// 时间戳转化成字符串日期格式
function formatTime(time) {
  if (!time) {
    return ' ';
  }
  var date = new Date(time);
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}

// tip自定义弹框   util.tipModal(this,"手机格式错误！");
const tipModal=(that,msg)=> {
  that.setData({ "tipitem.isShow": true,"tipitem.text":msg });
  setTimeout(function () {
    that.setData({ "tipitem.isShow": false });
  }, 2000)
}

module.exports = {
  requestGet: requestGet,
  requestPost: requestPost,
  getCurrentPageUrl: getCurrentPageUrl,
  formatTime: formatTime,
  tipModal:tipModal
}
